package com.yincb.config;


import com.yincb.constans.DataSourceConstants;
import com.yincb.dynamic.DynamicDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
@Configuration
@PropertySource("classpath:jdbc.properties")
@MapperScan("com.yincb.entity.mapper")
public class DynamicDataSourceConfig {


    @Bean(DataSourceConstants.DS_KEY_YCB01)
    @ConfigurationProperties(prefix = "spring.datasource.ycb01")
    public DataSource ycb01DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(DataSourceConstants.DS_KEY_YCB02)
    @ConfigurationProperties(prefix = "spring.datasource.ycb02")
    public DataSource ycb02DataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean
    @Primary
    public DataSource dynamicDataSource(){
        Map<Object, Object> dataSourceMap = new HashMap<>(2);
        dataSourceMap.put(DataSourceConstants.DS_KEY_YCB01,ycb01DataSource());
        dataSourceMap.put(DataSourceConstants.DS_KEY_YCB02,ycb02DataSource());
        //设置动态数据源
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(ycb01DataSource());
        return dynamicDataSource;
    }



}
